package org.example;


import org.example.bean.Cord;
import org.example.bean.Polygon;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D;
import java.util.List;

public class PolygonDrawer extends JFrame {

    private static final int CELL_SIZE = 5; // 单元格大小

    private List<Polygon> polygons;
    private int mapWidth;
    private int mapHeight;

    public PolygonDrawer(List<Polygon> polygons, int mapWidth, int mapHeight) {
        this.polygons = polygons;
        this.mapWidth = mapWidth;
        this.mapHeight = mapHeight;

        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(mapWidth * CELL_SIZE, mapHeight * CELL_SIZE); // 假设每个格子绘制为10x10像素
        setLocationRelativeTo(null); // 居中显示窗口  

        // 添加绘制面板  
        add(new DrawingPanel());

        setVisible(true);
    }

    private class DrawingPanel extends JPanel {

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 绘制地图格子（可选，这里只是绘制一个灰色背景）  
            g2d.setColor(Color.LIGHT_GRAY);
            for (int i = 0; i <= mapWidth; i++) {
                g2d.drawLine(i * CELL_SIZE, 0, i * CELL_SIZE, mapHeight * CELL_SIZE);
            }
            for (int i = 0; i <= mapHeight; i++) {
                g2d.drawLine(0, i * CELL_SIZE, mapWidth * CELL_SIZE, i * CELL_SIZE);
            }

            // 绘制多边形  
            for (Polygon polygon : polygons) {
                drawPolygon(g2d, polygon);
            }
        }

        private void drawPolygon(Graphics2D g2d, Polygon polygon) {
            Path2D path = new GeneralPath();
            boolean first = true;
            for (Cord point : polygon.getList()) {
                if (first) {
                    path.moveTo(point.getX() * CELL_SIZE, point.getY() * CELL_SIZE); // 假设每个格子绘制为10x10像素
                    first = false;
                } else {
                    path.lineTo(point.getX() * CELL_SIZE, point.getY() * CELL_SIZE);
                }
            }
            path.closePath(); // 确保多边形是闭合的  
            g2d.setColor(Color.RED); // 设置多边形颜色为红色  
            g2d.draw(path); // 绘制多边形轮廓  
            // 如果需要填充多边形，可以取消注释下一行  
            // g2d.fill(path);  
        }
    }


}